package com.hanbang.taitaigou.ui.activity.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.model.BannerAdData;
import com.hanbang.taitaigou.model.CommodityClassifyData;
import com.hanbang.taitaigou.model.GoodListData;
import com.hanbang.taitaigou.ui.activity.application.MyApplication;
import com.hanbang.taitaigou.ui.activity.base.MainBaseActivity;
import com.hanbang.taitaigou.ui.activity.home.OneMenu.JKZQActivity;
import com.hanbang.taitaigou.ui.activity.home.OneMenu.SGSXActivity;
import com.hanbang.taitaigou.ui.activity.home.OneMenu.XHLPActivity;
import com.hanbang.taitaigou.ui.activity.home.ThreeMenu.BaoKuanActivity;
import com.hanbang.taitaigou.ui.activity.home.ThreeMenu.SXSGActivity;
import com.hanbang.taitaigou.ui.activity.home.ThreeMenu.TeJiaActivity;
import com.hanbang.taitaigou.ui.activity.home.ThreeMenu.XRBYActivity;
import com.hanbang.taitaigou.ui.activity.home.ThreeMenu.YYZQActivity;
import com.hanbang.taitaigou.ui.activity.taitaigou.ProductDetailsActivity;
import com.hanbang.taitaigou.ui.activity.taitaigou.TaiTaiGouActivity;
import com.hanbang.taitaigou.ui.adapter.BannerAdAdapter;
import com.hanbang.taitaigou.ui.widget.GridViewForScrollView;
import com.hanbang.taitaigou.ui.widget.ListViewForScrollView;
import com.hanbang.taitaigou.ui.widget.NumberSelectView;
import com.hanbang.taitaigou.ui.widget.ScaleImageView;
import com.hanbang.taitaigou.ui.widget.XTextView;
import com.hanbang.taitaigou.ui.widget.banner.ConvenientBanner;
import com.hanbang.taitaigou.utils.db.GwcDbUtil;
import com.hanbang.taitaigou.utils.http.BitmapUtil;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpLocalUtils;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.http.JsonHelper;
import com.hanbang.taitaigou.utils.http.PagingHelp;
import com.hanbang.taitaigou.utils.other.StringUtils;
import com.hanbang.taitaigou.utils.ui.LogUtils;
import com.hanbang.taitaigou.utils.ui.ToastUtils;
import com.hanbang.taitaigou.utils.ui.UiUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends MainBaseActivity {
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    //经度
    private double locationLng;
    //纬度
    private double locationLat;
    //街道
    private String address;

    //主页轮播图片
    private ConvenientBanner convenientBanner = null;
    private ArrayList<BannerAdData> bannerAdDatas = new ArrayList<>();
    private BannerAdAdapter bannerAdAdapter = null;

    //货物分类GridView
//    private ArrayList<GridViewData> headList = new ArrayList<>();
    private ArrayList<CommodityClassifyData> goodsList = new ArrayList<>();
    private ArrayList<CommodityClassifyData> gridsList = new ArrayList<>();
    private GridViewForScrollView gridView = null;
    private GridViewAdapter gridAdapter;
    //货物分类详情
    private ListViewForScrollView lv_list;
    private ArrayList<GoodListData> fenleiList = new ArrayList<>();

    private int index;

    private String dizhi;

    //    private ArrayList<GoodsDetail> detail=new ArrayList();
    private PagingHelp pageHelp;
    private ListViewAdapter listAdapter = null;
    //ScrollView侧滑
    private ScrollView swipe_target = null;
    private SwipeRefreshLayout id_swip = null;
    private InnerGridViewAdapter innadapter;
    //titlebar
    ImageView top_bar_right_iv, top_bar_loc;
    private LinearLayout top_bar_right;
    TextView top_bar_title;
    public static String str = "";
    private int sell_id = -1;
    private int be_overdue_sell_id = -1;

    private ImageView home;
    private TextView tv_home;

    /**爆款**/
    private LinearLayout ll_baokuan;
    /**特价**/
    private LinearLayout ll_tejia;
    /**特产**/
    private LinearLayout ll_techan;

    private TextView tv_csbl,tv_sgsx,tv_xhlp,tv_smfu,tv_jkzq,tv_jqqd;
    private TextView tv_yiyuan,tv_sxsg,tv_tjcx,tv_xrby,tv_bkzq;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        initView();
        getInfomation(sell_id);
        setOnClickListener();
        getBannerImage();
        initBaiduLocation();
        fileOrder();
//        getLocalSJ();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("gaiAddress");
        registerReceiver(broadcastReceiver, intentFilter);

    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().toString().equals("gaiAddress")) {
                if (sell_id != be_overdue_sell_id) {
                    GwcDbUtil.clearAllGwc();
                }
                str = intent.getStringExtra("address");
                top_bar_title.setText(str);
                LogUtils.e("aaa", "111");
                getLocalSJ();
                File file = new File("data/data/com.hanbang.taitaigou/info.txt");
                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(file);
                    fos.write((top_bar_title.getText().toString()).getBytes());
                    fos.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };


    public void fileOrder() {
        File file = new File("data/data/com.hanbang.taitaigou/info.txt");
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                //把字节流转换成字符串
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                //读取文件里面的地址
                dizhi = br.readLine();
                if (dizhi != null) {
                    top_bar_title.setText(dizhi);
                    str = top_bar_title.getText().toString();
                    sengAddress(str);
                    getLocalSJ();
                } else {
                    if (!mLocationClient.isStarted()) {
                        mLocationClient.start();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (!mLocationClient.isStarted()) {
                mLocationClient.start();
            }
        }

    }

    //发送更改地址的广播
    private void sengAddress(String st) {
        Intent intent = new Intent();
        intent.setAction("sengAddress");
        intent.putExtra("str", st);
        sendBroadcast(intent);
        LogUtils.e("aabc", st.toString());


    }

    public void initBaiduLocation() {

        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            mLocationClient.stop();
            if (bdLocation.getLocType() == BDLocation.TypeGpsLocation || bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
                //gps或者网络  定位成功
                locationLng = bdLocation.getLongitude();
                locationLat = bdLocation.getLatitude();
                //街道
                if (!StringUtils.isBlank(bdLocation.getStreet())) {
                    address = bdLocation.getStreet();
                    LogUtils.e("aaa", "jsd");
                }
                if (!StringUtils.isBlank(bdLocation.getStreetNumber())) {
                    address += bdLocation.getStreetNumber();
                }
                top_bar_title.setText(address);
                str = top_bar_title.getText().toString();
                sengAddress(str);
                File file = new File("data/data/com.hanbang.taitaigou/info.txt");
                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(file);
                    fos.write((address).getBytes());
                    fos.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                //定位失败
                ToastUtils.showShort(MainActivity.this, "定位失败");
            }
        }
    }


    /*
     */
    public void setOnClickListener() {
        tv_csbl.setOnClickListener(onClickListener);
        tv_sgsx.setOnClickListener(onClickListener);
        tv_xhlp.setOnClickListener(onClickListener);
        tv_smfu.setOnClickListener(onClickListener);
        tv_jkzq.setOnClickListener(onClickListener);
        tv_jqqd.setOnClickListener(onClickListener);

        tv_yiyuan.setOnClickListener(onClickListener);
        tv_sxsg.setOnClickListener(onClickListener);
        tv_tjcx.setOnClickListener(onClickListener);
        tv_xrby.setOnClickListener(onClickListener);
        tv_bkzq.setOnClickListener(onClickListener);
    }

    @SuppressWarnings("unused")
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (v.getId()) {
                //超市遍历
                case R.id.tv_csbl:
                    intent.setClass(MainActivity.this,TaiTaiGouActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    startActivity(intent);
                    break;
                //水果生鲜
                case R.id.tv_sgsx:
                    intent.setClass(MainActivity.this, SGSXActivity.class);
                    startActivity(intent);
                    break;
                //鲜花礼品
                case R.id.tv_xhlp:
                    intent.setClass(MainActivity.this, XHLPActivity.class);
                    startActivity(intent);
                    break;
                //上门服务
                case R.id.tv_smfu:
                    ToastUtils.showShort(MainActivity.this,"这里是上门服务,功能正在开发中...");
                    break;
                //进口专区
                case R.id.tv_jkzq:
                    intent.setClass(MainActivity.this, JKZQActivity.class);
                    startActivity(intent);
                    break;
                //敬请期待
                case R.id.tv_jqqd:
                    ToastUtils.showShort(MainActivity.this,"正在建设中，敬请期待...");
                    break;
                //一元专区
                case R.id.tv_yiyuan:
                    intent.setClass(MainActivity.this, YYZQActivity.class);
                    startActivity(intent);
                    break;
                //生鲜水果
                case R.id.tv_sxsg:
                    intent.setClass(MainActivity.this, SXSGActivity.class);
                    startActivity(intent);
                    break;
                //特价促销
                case R.id.tv_tjcx:
                    intent.setClass(MainActivity.this, TeJiaActivity.class);
                    startActivity(intent);
                    break;
                //夏日冰饮
                case R.id.tv_xrby:
                    intent.setClass(MainActivity.this, XRBYActivity.class);
                    startActivity(intent);
                    break;
                //爆款专区
                case R.id.tv_bkzq:
                    intent.setClass(MainActivity.this, BaoKuanActivity.class);
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    };

    /*
     * 初始化view
     */
    private void initView() {

        tv_home = (TextView) findViewById(R.id.tv_home);
        tv_home.setTextColor(getResources().getColor(R.color.black));
        home = (ImageView) findViewById(R.id.home);
        home.setImageResource(R.mipmap.home_1);



        // 设置顶部的标题
//        setTop(null, 0, getString(R.string.botton_tab1), null, 0);
        top_bar_loc = (ImageView) findViewById(R.id.top_bar_loc);
        top_bar_right_iv = (ImageView) findViewById(R.id.top_bar_right_iv);
        top_bar_title = (TextView) findViewById(R.id.top_bar_title);
        top_bar_right = (LinearLayout)findViewById(R.id.top_bar_right);


        str = top_bar_title.getText().toString();
        sengAddress(str);
        setCurrentBotton(1);
        gridView = (GridViewForScrollView) findViewById(R.id.gridView);
        lv_list = (ListViewForScrollView) findViewById(R.id.lv_list);
        swipe_target = (ScrollView) findViewById(R.id.swipe_target);
        convenientBanner = (ConvenientBanner) findViewById(R.id.banner);

        ll_baokuan = (LinearLayout)findViewById(R.id.ll_baokuan);
        ll_tejia = (LinearLayout)findViewById(R.id.ll_tejia);
        ll_techan = (LinearLayout)findViewById(R.id.ll_techan);

//        private TextView tv_csbl,tv_sgsx,tv_xhlp,tv_smfu,tv_jkzq,tv_jqqd;
        tv_csbl = (TextView) findViewById(R.id.tv_csbl);
        tv_sgsx = (TextView) findViewById(R.id.tv_sgsx);
        tv_xhlp = (TextView) findViewById(R.id.tv_xhlp);
        tv_smfu = (TextView) findViewById(R.id.tv_smfu);
        tv_jkzq = (TextView) findViewById(R.id.tv_jkzq);
        tv_jqqd = (TextView) findViewById(R.id.tv_jqqd);

//        private TextView tv_yiyuan,tv_sxsg,tv_tjcx,tv_xrby,tv_bkzq;
        tv_yiyuan = (TextView) findViewById(R.id.tv_yiyuan);
        tv_sxsg = (TextView) findViewById(R.id.tv_sxsg);
        tv_tjcx = (TextView) findViewById(R.id.tv_tjcx);
        tv_xrby = (TextView) findViewById(R.id.tv_xrby);
        tv_bkzq = (TextView) findViewById(R.id.tv_bkzq);


        /**
         * 点击定位,定位到当前位置
         */
        top_bar_loc.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showShort(MainActivity.this,"正在定位中...");
                mLocationClient.start();
                fileOrder();
            }
        });

        top_bar_right.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SearchActivity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
            }
        });
        top_bar_title.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin(true)) {
                    //实现界面跳转
                    Intent intent = new Intent(MainActivity.this, AddAddressActivity.class);
//                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    startActivityForResult(intent, 999);
                }
            }
        });


        /**
         * 广告条初始化
         */
        bannerAdAdapter = new BannerAdAdapter(this,
                (RelativeLayout) findViewById(R.id.swipe_banner), bannerAdDatas);


        bannerAdAdapter.setOnItemClickListener(new BannerAdAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (bannerAdDatas.get(position).getContent_type() == 1) {
                    Intent intent = new Intent();
                    intent.putExtra("id", String.valueOf(bannerAdDatas.get(position).getContent_id()));
                    intent.putExtra("type", 1);
                    intent.setClass(MainActivity.this, ProductDetailsActivity.class);
                    startActivity(intent);
                } else if (bannerAdDatas.get(position).getContent_type() == 2) {
                    TaiTaiGouActivity.startUi(MainActivity.this, bannerAdDatas.get(position).getContent_id());
                }
            }
        });

        id_swip = (SwipeRefreshLayout) findViewById(R.id.id_swip);
        id_swip.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (isLogin(false)) {
                    getLocalSJ();
//                    if (!mLocationClient.isStarted()) {
//                        mLocationClient.start();
//                        LogUtils.e("aaa","aaa");
//                    }
                } else {
                    getInfomation(sell_id);
                }

            }
        });
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TaiTaiGouActivity.startUi(MainActivity.this, gridsList.get(position).getDept_id());
            }
        });

        ll_baokuan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, BaoKuanActivity.class);
                startActivity(intent);
            }
        });
        ll_tejia.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,TeJiaActivity.class);
                startActivity(intent);
            }
        });
        ll_techan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,TeChanActivity.class);
                startActivity(intent);
            }
        });
    }


    /**
     * 主页的请求
     */
    private void getInfomation(int seller_id) {


        Log.i("COMMON", "请求方法执行了");
        HttpRequestParams httpRequestParams = new HttpRequestParams("GetHomePage");
        if (seller_id != -1) {
            httpRequestParams.addBodyParameter("seller_id", seller_id + "");
        }
        LogUtils.i("rrsadarrr", "seller_id的值是：" + seller_id);
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, "正在加载...") {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    goodsList.clear();
                    gridsList.clear();
                    fenleiList.clear();
                    JSONObject json = new JSONObject(result);
                    JSONArray array = json.getJSONArray("result");
                    goodsList.addAll(JsonHelper.parseCollection(array, ArrayList.class, CommodityClassifyData.class));
                    gridsList.addAll(JsonHelper.parseCollection(array, ArrayList.class, CommodityClassifyData.class));

                    for (int i = 0; i < gridsList.size(); i++) {
                        fenleiList.addAll(gridsList.get(i).getGoods_detail());
                    }
                    if (fenleiList.size() > 0) {
                        MyApplication.shangjiaId = fenleiList.get(0).getStore_id();
                        LogUtils.e("id1111888881", MyApplication.shangjiaId + "");

                    } else {
                        MyApplication.shangjiaId = sell_id;
                        Intent intent = new Intent();
                        intent.setAction("setTranslate");
                        sendBroadcast(intent);
                    }
                    GwcDbUtil.setDataDbSelectNumber(fenleiList);
                    //GridView设置适配器
                    gridAdapter = new GridViewAdapter(gridsList);
                    gridView.setAdapter(gridAdapter);
                    gridAdapter.notifyDataSetChanged();
                    //ListVAdapter设置适配器
                    listAdapter = new ListViewAdapter(goodsList);
                    lv_list.setAdapter(listAdapter);
                    listAdapter.notifyDataSetChanged();

                } catch (JSONException e) {

                }
            }
        }.setSwipeRefreshLayout(id_swip));
    }

    @Override
    protected void onResume() {
        super.onResume();
//开始自动翻页
//        convenientBanner.startTurning(2000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /*
        * 设置GridView的Adapter
        * */
    class GridViewAdapter extends BaseAdapter {
        private List<CommodityClassifyData> grList = new ArrayList<>();

        public GridViewAdapter(List<CommodityClassifyData> grList) {
//            this.grList.clear();
            this.grList = grList;
        }

        @Override
        public int getCount() {
            return grList.size();

        }

        @Override
        public Object getItem(int position) {
            return grList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.grid_item, null);
                viewHolder.goodImage = (ScaleImageView) convertView.findViewById(R.id.goodImage);
                viewHolder.goodText = (TextView) convertView.findViewById(R.id.goodText);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            LogUtils.e("aaa", grList.get(position).getImg_url());
            viewHolder.goodText.setText(grList.get(position).getTitle());
            imageManager.bind(viewHolder.goodImage, HttpLocalUtils.getHttpFileUrl(grList.get(position).getImg_url()), BitmapUtil.getImageOptionsBuilder().build());
            return convertView;
        }

        class ViewHolder {
            ScaleImageView goodImage;
            TextView goodText;
        }
    }

    /*
       * 设置ListView的Adapter
       * */
    class ListViewAdapter extends BaseAdapter {
        private ArrayList<CommodityClassifyData> gList = new ArrayList<>();

        public ListViewAdapter(ArrayList<CommodityClassifyData> gList) {
            this.gList.clear();
            this.gList = gList;
            for (int i = 0; i < gList.size(); i++) {
                if (gList.get(i).getGoods_detail().size() == 0) {
//                    ToastUtils.show(MainActivity.this, "最近的商家沒有货哦", ToastUtils.LENGTH_SHORT);
                    gList.remove(i);
                    i--;
                }
            }
            LogUtils.i("yuyuyu", "goodsList的数据是:" + gList.toString());
        }

        @Override
        public int getCount() {
            if (gList.size() <= 0) {
                ToastUtils.show(MainActivity.this, "最近的商家沒有货哦", ToastUtils.LENGTH_SHORT);
            }
            return gList.size();
        }

        @Override
        public Object getItem(int position) {
            return gList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.home_listview_item, null);
                viewHolder.tv_goodtype = (TextView) convertView.findViewById(R.id.tv_goodtype);
                viewHolder.image = (ImageView) convertView.findViewById(R.id.image);
                viewHolder.goodgrid = (GridView) convertView.findViewById(R.id.goodgrid);
                viewHolder.link_layout = (LinearLayout) convertView.findViewById(R.id.link_layout);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.tv_goodtype.setText(gList.get(position).getTitle().toString());
            imageManager.bind(viewHolder.image, HttpLocalUtils.getHttpFileUrl(gList.get(position).getLink_url()), BitmapUtil.getImageOptionsBuilder().setImageScaleType(ImageView.ScaleType.FIT_XY).build());
            innadapter = new InnerGridViewAdapter(gList.get(position).getGoods_detail(), position);
            viewHolder.goodgrid.setAdapter(innadapter);

            LogUtils.i("qqqq", "货物详情为：" + gList.get(position).getGoods_detail().toString());
            viewHolder.link_layout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    TaiTaiGouActivity.startUi(MainActivity.this, gList.get(position).getDept_id());
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView tv_goodtype;
            ImageView image;
            GridView goodgrid;
            LinearLayout link_layout;
        }
    }


    /**
    获取首页轮播图片请求方法
    * */
    private void getBannerImage() {
        HttpRequestParams httpRequestParams = new HttpRequestParams("GetHomePageImg");
        httpRequestParams.addBodyParameter("pageindex", "1");
        httpRequestParams.addBodyParameter("pagesize", "10");
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, "正在加载...") {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject json = new JSONObject(result);
                    JSONArray array = json.getJSONArray("result");
                    for (int i = 0; i < array.length(); i++) {
                        BannerAdData bid = new BannerAdData();
                        bid.setContent_id(array.getJSONObject(i).getInt("content_id"));
                        bid.setContent_type(array.getJSONObject(i).getInt("content_type"));
                        bid.setImg_url(array.getJSONObject(i).getString("img_url"));
                        bannerAdDatas.add(bid);
                    }
                    bannerAdAdapter.notifyDataSetChanged();
                    bannerAdAdapter.start();

                    LogUtils.e("获取的url------->", "   " + bannerAdDatas.get(0).getImg_url());
                } catch (JSONException e) {

                }
            }
        });
    }


    /**
     * 内部GridViewAdapter
     */
    class InnerGridViewAdapter extends BaseAdapter {
        private List<GoodListData> gridlist = new ArrayList<>();
        private int g_position;

        public InnerGridViewAdapter(List<GoodListData> gridlist, int position) {
            this.gridlist.clear();
            this.gridlist = gridlist;
            this.g_position = position;
        }


        @Override
        public int getCount() {
            return gridlist.size();
        }

        @Override
        public Object getItem(int position) {
            return gridlist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            ViewHolder viewHolder;
            final GoodListData itemData = (GoodListData) getItem(position);
//            CommodityClassifyData comData = goodsList.get(position);
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = UiUtils.getInflaterView(MainActivity.this, R.layout.home_list_griditem);
                viewHolder.grid_image = (ScaleImageView) convertView.findViewById(R.id.grid_image);
                viewHolder.tv_gname = (TextView) convertView.findViewById(R.id.tv_gname);
                viewHolder.tv_gunit = (TextView) convertView.findViewById(R.id.tv_gunit);
                viewHolder.sell_price = (TextView) convertView.findViewById(R.id.sell_price);
                viewHolder.tv_oriprice = (XTextView) convertView.findViewById(R.id.tv_oriprice);
                viewHolder.jiahao = (ImageView)convertView.findViewById(R.id.jiahao);
//                viewHolder.number_select_view = (NumberSelectView) convertView.findViewById(R.id.number_select_view);
                viewHolder.grid_layout = (LinearLayout) convertView.findViewById(R.id.grid_layout);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            //获取数据
            imageManager.bind(viewHolder.grid_image, HttpLocalUtils.getHttpFileUrl(gridlist.get(position).getImg_url()), BitmapUtil.getImageOptionsBuilder().build());
            viewHolder.tv_gname.setText(gridlist.get(position).getGname());
            viewHolder.tv_gunit.setText("规格：" + gridlist.get(position).getPknum() + (gridlist.get(position).getUnit() == null ? "" : "/" + gridlist.get(position).getUnit()));
            viewHolder.sell_price.setText("¥" + gridlist.get(position).getSell_price());
            viewHolder.tv_oriprice.setText("¥" + gridlist.get(position).getOriginal_price());
            viewHolder.grid_layout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, ProductDetailsActivity.class);
                    intent.putExtra("id", gridlist.get(position).getId() + "");
                    intent.putExtra("title", goodsList.get(g_position).getTitle());
                    intent.putExtra("User_id", MyApplication.shangjiaId);
                    startActivity(intent);
                    LogUtils.i("eeee", "传过去的Dept_id是：" + goodsList.get(g_position).getDept_id());
                    innadapter.notifyDataSetChanged();
                }
            });
            viewHolder.jiahao.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (GwcDbUtil.addGoodAutoNumber(itemData.getDbGwcData())) {
                        itemData.setNumber(itemData.getNumber() + 1);
                        innadapter.notifyDataSetChanged();
                    }
                }
            });
            return convertView;
        }

        class ViewHolder {
            ScaleImageView grid_image = null;
            TextView tv_gname = null;
            TextView tv_gunit = null;
            TextView sell_price = null;
            XTextView tv_oriprice = null;
            NumberSelectView number_select_view = null;
            LinearLayout grid_layout;
            ImageView jiahao;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999 && resultCode == 1001) {
            top_bar_title.setText(data.getStringExtra("address"));
            str = top_bar_title.getText().toString();
            sengAddress(str);

            if (sell_id != be_overdue_sell_id) {
                GwcDbUtil.clearAllGwc();
            }
            LogUtils.e("aaa", "111");
            getLocalSJ();
            File file = new File("data/data/com.hanbang.taitaigou/info.txt");
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(file);
                fos.write((top_bar_title.getText().toString()).getBytes());
                fos.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

    public void getLocalSJ() {
        HttpRequestParams httpRequestParams = new HttpRequestParams("RecentMerchant");
        LogUtils.i("mmm", "传进来的User_id是：" + userData.getUser_id());
        httpRequestParams.addBodyParameter("User_id", userData.getUser_id() + "");
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, "正在加载...") {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject json = new JSONObject(result);
                    be_overdue_sell_id = sell_id;
                    sell_id = json.getInt("result");
                    LogUtils.i("ddddsadasd", "这里的sell_id是：" + json.getInt("result"));
                    getInfomation(sell_id);
                } catch (JSONException e) {
                }
            }
        });
    }
}